<?php

namespace EasySwoole\EasySwoole;

use EasySwoole\Component\Di;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\FastCache\Cache;
use EasySwoole\HotReload\HotReload;
use EasySwoole\HotReload\HotReloadOptions;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\Db\Config as ConfigOrm;
use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\DbManager;
use Swoole\Coroutine\Scheduler;
use Swoole\Timer;
use const EASYSWOOLE_ROOT;

class EasySwooleEvent implements Event {

    /**
     * 框架初始化事件
     */
    public static function initialize() {
	date_default_timezone_set('Asia/Shanghai');

	//注册数据库连接
	$config = new ConfigOrm(Config::getInstance()->getConf("MYSQL"));
	DbManager::getInstance()->addConnection(new Connection($config));

	// 创建一个协程调度器
	$scheduler = new Scheduler();
	$scheduler->add(function () {
	    $builder = new QueryBuilder();
	    $builder->where('status', 1)->fields('menu_name, value')->get('eb_system_config');
	    $sysConfig = DbManager::getInstance()->query($builder, true)->getResult();
	    if ($sysConfig) {
		Config::getInstance()->merge(array_column($sysConfig, 'value', 'menu_name'));
	    }
	    // 这边重置 ORM 连接池的 pool，避免连接被克隆到子进程，造成连接跨进程公用。
	    // DbManager 如果有注册多库连接，请记得一起 getConnection($name) 获取全部的 pool 去执行 reset
	    // 其他的连接池请获取到对应的 pool，然后执行 reset() 方法
	    DbManager::getInstance()->getConnection()->__getClientPool()->reset();
	});
	//执行调度器内注册的全部回调
	$scheduler->start();
	//清理调度器内可能注册的定时器，不要影响到swoole server 的event loop
	Timer::clearAll();

	//处理请求的跨域问题	
	Di::getInstance()->set(SysConst::HTTP_GLOBAL_ON_REQUEST, function (Request $request, Response $response) {
	    $origin = $request->getHeader('origin')[0] ?? '*';
	    $response->withHeader('Access-Control-Allow-Origin', $origin);
	    $response->withHeader('Access-Control-Allow-Methods', 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE');
	    $response->withHeader('Access-Control-Allow-Credentials', 'true');
	    $response->withHeader('Access-Control-Max-Age', '1728000');
	    $response->withHeader('Access-Control-Allow-Headers', 'Authori-zation,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With, Form-type');

	    if ($request->getMethod() === 'OPTIONS') {
		$response->withStatus(\EasySwoole\Http\Message\Status::CODE_OK);
		return false;
	    }
	});
    }

    /**
     * 主服务创建事件
     * @param EventRegister $register
     */
    public static function mainServerCreate(EventRegister $register) {
	$server = ServerManager::getInstance()->getSwooleServer();

	$register->add($register::onWorkerStart, function () {
	    // 数据库链接预热
	    DbManager::getInstance()->getConnection()->__getClientPool()->keepMin();
	});

	//Fastcache，注意新版本数据不落地
	$config = new \EasySwoole\FastCache\Config();
	$config->setTempDir(EASYSWOOLE_TEMP_DIR);
	Cache::getInstance($config)->attachToServer($server);

	//热加载
	$hotReloadOptions = new HotReloadOptions;
	$hotReload = new HotReload($hotReloadOptions);
	$hotReloadOptions->setMonitorFolder([EASYSWOOLE_ROOT . '/App']);
	$hotReload->attachToServer($server);
    }

}
